using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Xml;
using Microsoft.DesignerSupport;
using System.Reflection;

namespace XMTAEditor
{
	public partial class Form1 : Form
	{
		NetCFMetadata xmtaMD, asmMD;

		public Form1()
		{
			AppDomain.CurrentDomain.AssemblyResolve += new ResolveEventHandler(CurrentDomain_AssemblyResolve);
			InitializeComponent();
		}

		public static Assembly CurrentDomain_AssemblyResolve(object sender, ResolveEventArgs e)
		{
			ModuleLoadForm f = new ModuleLoadForm();
			string s = f.ShowDialog(e.Name);
			if (s != null)
			{
				return Assembly.LoadFrom(s);
			}
			throw new ApplicationException();
		}

		private void Form1_Load(object sender, EventArgs e)
		{
		}

		private void openToolStripMenuItem_Click(object sender, EventArgs e)
		{
			openFileDialog1.Title = "Open XMTA File";
			openFileDialog1.Filter = "XMTA files|*.xmta|All files|*.*";
			if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
			{
				LoadXMTA(openFileDialog1.FileName);
			}
		}

		private void LoadXMTA(string filename)
		{
			xmtaMD = MetadataFactory.FromXml(filename);
			SetControlMetadata();
		}

		private void LoadAsm(string filename)
		{
			asmMD = MetadataFactory.FromAssembly(filename);
			SetControlMetadata();
		}

		private void SetControlMetadata()
		{
			this.xmtaEditControl1.Metadata = MetadataFactory.Merge(xmtaMD, asmMD);
		}

		private void exitToolStripMenuItem_Click(object sender, EventArgs e)
		{
			Application.Exit();
		}

		private void openAssemblyToolStripMenuItem_Click(object sender, EventArgs e)
		{
			openFileDialog1.Title = "Open Assembly";
			openFileDialog1.Filter = "Assemblies|*.dll;*.exe|All files|*.*";
			if (openFileDialog1.ShowDialog(this) == DialogResult.OK)
			{
				LoadAsm(openFileDialog1.FileName);
			}
		}

		private void resetToolStripMenuItem_Click(object sender, EventArgs e)
		{
			asmMD = xmtaMD = null;
			SetControlMetadata();
		}

		private void saveAsToolStripMenuItem_Click(object sender, EventArgs e)
		{
			if (saveFileDialog1.ShowDialog(this) == DialogResult.OK)
			{
				xmtaEditControl1.Save(saveFileDialog1.FileName);
			}
		}
	}
}